package com.lc.module;

import android.content.Context;
import android.os.Environment;

import com.lc.protocol.DeviceError;
import com.lc.command.ICommandDriver;
import com.lc.tool.AppHelper;

import org.json.JSONException;
import org.json.JSONObject;

/**
 * Created by zhyioo on 2017/4/25.
 */

public class AppCmdDriver implements ICommandDriver {

    protected Context _context = null;

    public AppCmdDriver(Context context) {
        _context = context;
    }

    @Override
    public boolean OnCommand(String cmd, JSONObject arg, JSONObject rlt) {
        boolean bOK = true;
        if (cmd.equalsIgnoreCase("LocalFolder")) {
            try {
                rlt.put("Folder", _context.getFilesDir().getPath());
            } catch (JSONException e) {
                bOK = false;
            }
        } else if (cmd.equalsIgnoreCase("PackageCodePath")) {
            try {
                rlt.put("Path", _context.getPackageCodePath());
            } catch (JSONException e) {
                bOK = false;
            }
        } else if(cmd.equalsIgnoreCase("ReadText")) {
            String path = arg.optString("Path");
            try {
                rlt.put("Text", AppHelper.ReadText(path));
            } catch (JSONException e) {
                bOK = false;
            }
        } else if(cmd.equalsIgnoreCase("GetStorageCardDir")) {
            String sType = arg.optString("Type", "");
            String path = Environment.getExternalStoragePublicDirectory(sType).getAbsolutePath();
            try {
                rlt.put("Path", path);
            } catch (JSONException e) {
                bOK = false;
            }
        } else if(cmd.equalsIgnoreCase("WriteText")) {
            String path = arg.optString("Path");
            String text = arg.optString("Text");
            bOK = AppHelper.WriteText(path, text);
        } else if(cmd.equalsIgnoreCase("RequestROOT")) {
            bOK = AppHelper.UpgradeRootPermission("chmod 777 " + _context);
        } else if(cmd.equalsIgnoreCase("Toast")) {
            AppHelper.Toast(_context, arg);
        } else if(cmd.equalsIgnoreCase("Console")) {
            String consoleCmd = arg.optString("CMD", "");
            boolean isRoot = arg.optBoolean("IsRoot", false);

            if(!consoleCmd.isEmpty()) {
                if(isRoot) {
                    bOK = AppHelper.UpgradeRootPermission(consoleCmd);
                } else {
                    bOK = AppHelper.OnCommand(consoleCmd);
                }
            }
        }
        try {
            rlt.put("CODE", bOK ? DeviceError.Success : DeviceError.OperatorErr);
        } catch (JSONException e) {

        }
        return bOK;
    }
}
